<template>
	<div class="edit-page-wrap">
		<Head title="基础信息">
			<template #content>
				<el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="140px" class="edit-form-wrap">
					<el-form-item label="电站名称" prop="stationName">
						<el-input v-if="!id" v-model.trim="ruleForm.stationName" placeholder="请输入电站名称" maxlength="30"
							clearable />
						<div v-else>{{ ruleForm.stationName }}</div>
					</el-form-item>
					<el-form-item label="归属运营商" prop="operatorId">
						<qc-select v-if="!id" :value="ruleForm.operatorId" :remote="true" :filterable="true"
							:options="optionsS.org" placeholder="请选择归属运营商" @change="handleChangeOrg">
						</qc-select>
						<div v-else>{{ ruleForm.operatorName || '--' }}</div>
					</el-form-item>
					<el-form-item label="运营状态" prop="stationStatus">
						<qc-select :value="ruleForm.stationStatus" :options="optionsS.stationStatus"
							placeholder="请选择运营状态" @change="handleChangeOrgStatus">
						</qc-select>
					</el-form-item>
					<el-form-item label="电站地址" prop="regionCodes">
						<el-cascader ref="regionRef" popper-class="qc-cascader" v-model="ruleForm.regionCodes"
							:options="optionsS.region" @change="handleChangeRregion" placeholder="请选择省市区" clearable />
					</el-form-item>
					<el-form-item label="" prop="address">
						<el-input v-model.trim="ruleForm.address" placeholder="请输入详情地址" maxlength="50" clearable />
						<el-button type="primary" class="item-btn" @click="clickAddress">地图定位</el-button>
					</el-form-item>
					<div class="address-wrap">
						<el-form-item>
							<el-input class="input-wrap" v-model.trim="ruleForm.stationLng" placeholder="请输入经度"
								maxlength="10" clearable @input="changeLngLat">
								<template #prepend>经度</template>
							</el-input>
						</el-form-item>
						<el-form-item :label-width="12">
							<el-input class="input-wrap" v-model.trim="ruleForm.stationLat" placeholder="请输入纬度"
								maxlength="10" clearable @input="changeLngLat">
								<template #prepend>纬度</template>
							</el-input>
						</el-form-item>
					</div>
					<el-form-item label="">
						<Map v-if="mapType === 'gd'" ref="mapRef" @set-location="setLocation"
							@set-region="setRegion"></Map>
						<QMap v-else ref="mapRef" @set-location="setLocation" @set-region="setRegion"></QMap>
					</el-form-item>
					<el-form-item label="电站位置" prop="stationAddress">
						<el-radio-group v-model="ruleForm.stationAddress"
							v-for="(item, index) in optionsS.stationAddress" :key="index">
							<el-radio :label="item.value">{{ item.label }}</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="是否增容" prop="isIncrease">
						<el-radio-group v-model="ruleForm.isIncrease" v-for="(item, index) in STATION_INCREASE"
							:key="index">
							<el-radio :label="item.value">{{ item.label }}</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="可用电容" prop="capacitance">
						<el-input v-model.trim="ruleForm.capacitance" placeholder="请输入可用电容" maxlength="30" clearable>
							<template #append>KV-A</template>
						</el-input>
					</el-form-item>
					<el-form-item label="场地属性" prop="property">
						<el-radio-group v-model="ruleForm.property" v-for="(item, index) in optionsS.property"
							:key="index">
							<el-radio :label="item.value">{{ item.label }}</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="电站类型" prop="stationType">
						<qc-select :value="ruleForm.stationType" :options="optionsS.stationType" placeholder="请选择电站类型"
							@change="handleChangeType">
						</qc-select>
					</el-form-item>
					<el-form-item label="建设场所" prop="construction">
						<qc-select :value="ruleForm.construction" :options="optionsS.construction" placeholder="请选择建设场所"
							@change="handleChangeConstruction">
						</qc-select>
					</el-form-item>
					<el-form-item label="移动端可见性" prop="isMobileVisible">
						<el-radio-group v-model="ruleForm.isMobileVisible" v-for="(item, index) in STATION_VISIBLE"
							:key="index">
							<el-radio :label="item.value">{{ item.label }}</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-form>
			</template>
		</Head>
		<Head title="充电单价">
			<template #tip>
				<div class="head-tip left-8">
					<div class="icon"></div>
					温馨提示：根据电桩协议版本，设置场站中适用该协议的电桩的计费模版，一个协议版本仅支持设置一个计费模板
				</div>
			</template>
			<template #content>
				<el-form :model="ruleForm" :rules="rules" label-width="140px" class="edit-form-wrap">
					<StationPrice ref="stationPriceRef" :operatorId="ruleForm.operatorId" @show-price="showPrice">
					</StationPrice>
				</el-form>
			</template>
		</Head>
		<Head title="服务费分润设置">
			<template #content>
				<el-form ref="ruleFormShareRef" :model="ruleForm" :rules="rules" label-width="140px"
					class="edit-form-wrap">
					<el-form-item label="分润模式" prop="shareType">
						<el-radio-group v-model="ruleForm.shareType" v-for="(item, index) in optionsS.shareType"
							:key="index" @change="changeShareType" :disabled="Boolean(id)">
							<el-radio :label="item.value">{{ item.label }}</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item v-if="ruleForm.shareType === '1'" label="分润方设置" class="has-tips">
						<el-input v-model.trim="shareValue" placeholder="请输入" maxlength="30" clearable disabled>
							<template #prepend>运营商分润比例</template>
							<template #append>%</template>
						</el-input>
						<el-button v-if="!isPercentage" type="primary" class="item-btn" @click="clickAdd">增加</el-button>
						<div class="tip">
							<div class="icon"></div>
							注：运营商分润金额为所有分润方分完后剩余金额
						</div>
					</el-form-item>
					<el-form-item v-if="ruleForm.shareType === '1' && isPercentage" label="">
						<SharePercentage ref="sharePercentageRef" @set-percentage="setPercentage"
							@total-percentage="totalPercentage"></SharePercentage>
					</el-form-item>
					<el-form-item v-if="ruleForm.shareType === '2'" label="分润方设置">
						<SharePrice ref="sharePriceRef"></SharePrice>
					</el-form-item>
				</el-form>
			</template>
		</Head>
		<Head title="占用收费设置（充电完成规定时间未拔枪）">
			<template #content>
				<el-form ref="ruleFormSiteRef" :model="ruleForm" :rules="rules" label-width="140px"
					class="edit-form-wrap">
					<el-form-item label="是否收取占用费" prop="isOccupationCost">
						<el-radio-group v-model="ruleForm.isOccupationCost" v-for="(item, index) in STATION_SITE"
							:key="index">
							<el-radio :label="item.value">{{ item.label }}</el-radio>
						</el-radio-group>
					</el-form-item>
					<div v-if="ruleForm.isOccupationCost">
						<el-form-item label="停车缓冲时长" prop="parkBufferTime">
							<el-input v-model.trim="ruleForm.parkBufferTime" placeholder="请输入预留给用户充完电拔枪离场时长"
								maxlength="9" clearable>
								<template #append>分钟</template>
							</el-input>
						</el-form-item>
						<div class="site-wrap">
							<el-form-item label="超时计费" prop="overtimeMoney">
								<el-input class="input-wrap" v-model.trim="ruleForm.overtimeMoney" placeholder="单价"
									maxlength="30" clearable>
									<template #append>元</template>
								</el-input>
							</el-form-item>
							<div style="padding: 0 12px; line-height: 30px">/</div>
							<el-form-item label="" prop="overtimeMin" label-width="0">
								<el-input class="input-wrap" v-model.trim="ruleForm.overtimeMin" placeholder="时长"
									maxlength="9" clearable>
									<template #append>分钟</template>
								</el-input>
							</el-form-item>
						</div>
						<el-form-item label="单笔扣费上限" prop="singleDeductionLimit" class="has-tips">
							<el-input v-model.trim="ruleForm.singleDeductionLimit" placeholder="设置占用订单最大扣费金额"
								maxlength="30" clearable>
								<template #append>元</template>
							</el-input>
							<div class="tip">
								<div class="icon"></div>
								示例：设置扣费上限为10元，单笔占用订单计费为20元时，仅收取用户10元费用
							</div>
						</el-form-item>
					</div>
				</el-form>
			</template>
		</Head>
		<Head title="电站配置">
			<template #content>
				<el-form ref="ruleFormSetRef" :model="ruleForm" :rules="rules" label-width="140px"
					class="edit-form-wrap">
					<el-form-item label="场站道闸" prop="isBrake">
						<el-radio-group v-model="ruleForm.isBrake" v-for="(item, index) in STATION_BRAKE" :key="index">
							<el-radio :label="item.value">{{ item.label }}</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="停车说明" prop="parkExplain">
						<el-input v-model.trim="ruleForm.parkExplain" placeholder="请输入停车说明" maxlength="30" clearable />
					</el-form-item>
					<el-form-item label="站点描述" prop="stationDescribe">
						<el-input v-model.trim="ruleForm.stationDescribe" placeholder="请输入站点描述" maxlength="200"
							type="textarea" :rows="3" show-word-limit clearable />
					</el-form-item>
					<el-form-item label="站点服务设施" prop="serviceSetupArr">
						<qc-select :value="ruleForm.serviceSetupArr" :options="optionsS.serviceSetup"
							placeholder="请选择站点服务设施" multiple @change="handleChangeService">
						</qc-select>
					</el-form-item>
					<el-form-item label="周边基础设施" prop="baseSetupArr">
						<qc-select :value="ruleForm.baseSetupArr" :options="optionsS.baseSetup" placeholder="请选择周边基础设施"
							multiple @change="handleChangeBase">
						</qc-select>
					</el-form-item>
					<el-form-item label="开放时间说明" prop="openExplain">
						<el-input v-model.trim="ruleForm.openExplain" placeholder="请输入开放时间说明" maxlength="30"
							clearable />
					</el-form-item>
					<div class="address-wrap">
						<el-form-item label="电站图片" prop="imgMainEntrance">
							<QcUpload :valueModel="ruleForm.imgMainEntrance" @on-success="handleSuccessMainEntrance"
								@before-upload="beforeUploadMainEntrance" @on-error="handleErrorMainEntrance" tip=""
								title="主入口图"></QcUpload>
						</el-form-item>
						<el-form-item label="" prop="imgFlagPath" :label-width="36">
							<QcUpload :valueModel="ruleForm.imgFlagPath" @on-success="handleSuccessFlagPath"
								@before-upload="beforeUploadFlagPath" @on-error="handleErrorFlagPath" tip=""
								title="标志路径"></QcUpload>
						</el-form-item>
						<el-form-item label="" prop="imgFullView" :label-width="36">
							<QcUpload :valueModel="ruleForm.imgFullView" @on-success="handleSuccessFullView"
								@before-upload="beforeUploadFullView" @on-error="handleErrorFullView" tip=""
								title="电站全景"></QcUpload>
						</el-form-item>
						<el-form-item label="" prop="imgPilesFeature" :label-width="36">
							<QcUpload :valueModel="ruleForm.imgPilesFeature" @on-success="handleSuccessPilesFeature"
								@before-upload="beforeUploadPilesFeature" @on-error="handleErrorPilesFeature" tip=""
								title="电桩特写"></QcUpload>
						</el-form-item>
						<el-form-item label="" prop="imgOther" :label-width="36">
							<QcUpload :valueModel="ruleForm.imgOther" @on-success="handleSuccessOther"
								@before-upload="beforeUploadOther" @on-error="handleErrorOther" tip="" title="其他图片">
							</QcUpload>
						</el-form-item>
					</div>
					<el-form-item label="所属资质" prop="qualification">
						<QcUpload :valueModel="ruleForm.qualification" @on-success="handleSuccessQualification"
							@before-upload="beforeUploadQualification" @on-error="handleErrorQualification" tip="">
						</QcUpload>
					</el-form-item>
					<el-form-item label="备注说明" prop="remarks">
						<el-input v-model.trim="ruleForm.remarks" placeholder="请输入备注说明" maxlength="200" type="textarea"
							:rows="3" show-word-limit clearable />
					</el-form-item>
				</el-form>
			</template>
		</Head>
		<div class="edit-btn-wrap">
			<el-button type="primary" plain @click="back">取消</el-button>
			<el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
		</div>
		<DialogPrice ref="dialogPriceRef"></DialogPrice>
	</div>
</template>

<script lang="ts" setup>
	import Head from '@/components/head/index.vue';
	import QcUpload from '@/components/qcUpload/index.vue';
	import Map from '../components/map.vue';
	import QMap from '../components/qqMap.vue';
	import StationPrice from '../components/stationPrice.vue';
	import SharePercentage from '../components/sharePercentage.vue';
	import SharePrice from '../components/sharePrice.vue';
	import DialogPrice from '../components/dialogPrice.vue';
	import { FormInstance, FormRules } from 'element-plus';
	import { selectAllOperatorList } from '@/service/apis/org';
	import {
		addStation,
		updateStation,
		queryByOrgId,
		queryStationDetail,
	} from '@/service/apis/pile';
	import { queryDicByParent } from '@/service/apis/api';
	import { getRegion, bntAuth } from '@/utils/utils';
	import {
		STATION_INCREASE,
		STATION_VISIBLE,
		STATION_SITE,
		STATION_BRAKE,
	} from '@/utils/dictionaries';
	import { IS_DECIMAL_2, IS_INT_0, IS_INT } from '@/utils/verify';

	const mapType = import.meta.env.VITE_ENV_MAP;

	const router = useRouter();
	const route = useRoute();
	const {
		query: { id },
	} = route;

	const ruleFormRef = ref<FormInstance>();
	const ruleFormShareRef = ref<FormInstance>();
	const ruleFormSiteRef = ref<FormInstance>();
	const ruleFormSetRef = ref<FormInstance>();
	const stationPriceRef = ref();
	const sharePriceRef = ref();
	const sharePercentageRef = ref();
	const mapRef = ref();
	const dialogPriceRef = ref();

	let optionsS = reactive({
		org: [] as any,
		region: [] as any,
		stationStatus: [] as any,
		stationAddress: [] as any,
		property: [] as any,
		shareOrg: [] as any,
		stationType: [] as any,
		construction: [] as any,
		shareType: [] as any,
		serviceSetup: [] as any,
		baseSetup: [] as any,
	});

	queryDicByParent({
		listDtos: [
			'stationStatus',
			'stationAddress',
			'property',
			'stationType',
			'construction',
			'shareType',
			'serviceSetup',
			'baseSetup',
		],
	}).then((res : any) => {
		if (res) {
			console.log('ddd--', res);
			optionsS.stationStatus = res.stationStatus;
			optionsS.stationAddress = res.stationAddress;
			optionsS.property = res.property;
			optionsS.stationType = res.stationType;
			optionsS.construction = res.construction;
			optionsS.shareType = res.shareType;
			optionsS.serviceSetup = res.serviceSetup;
			optionsS.baseSetup = res.baseSetup;
		}
	});

	// 获取归属运营商
	selectAllOperatorList({}).then((res : any) => {
		if (res) {
			nextTick(() => {
				optionsS.org = [...res.listMap];
			});
		}
	});

	// 获取省市区
	getRegion().then((res : any) => {
		optionsS.region = res;
	});

	// 获取分润方数据
	const getOrgData = (val : any) => {
		return new Promise((resolve) => {
			queryByOrgId(val).then((res : any) => {
				if (res) {
					resolve([...res.dataList]);
				} else {
					resolve([]);
				}
			});
		});
	};

	// 获取详情回填数据
	if (id) {
		queryStationDetail({ id: id }).then(async (res : any) => {
			if (res) {
				for (const key in ruleForm) {
					if (res[key] || typeof res[key] === 'boolean') {
						ruleForm[key] = res[key];
					}
				}
				console.log('res---', res, ruleForm);
				ruleForm.regionCodes = [res.provinceCode, res.cityCode, res.areaCode];
				ruleForm.serviceSetupArr = ruleForm.serviceSetup.split(',');
				ruleForm.baseSetupArr = ruleForm.baseSetup.split(',');
				nextTick(() => {
					stationPriceRef.value?.setData(res.stationCostBatchNumberInfoPOList);
					if (ruleForm.stationLng && ruleForm.stationLat) {
						mapRef.value?.setMarker(ruleForm.stationLng, ruleForm.stationLat);
					}
				});
				if (ruleForm.shareType === '1') {
					if (res.stationServiceSets?.length > 0) {
						setPercentage(true);
						optionsS.shareOrg = await getOrgData(ruleForm.operatorId);
						nextTick(() => {
							sharePercentageRef.value?.setData(
								res.stationServiceSets,
								res.operatorId,
								optionsS.shareOrg
							);
						});
					}
				} else {
					optionsS.shareOrg = await getOrgData(ruleForm.operatorId);
					nextTick(() => {
						sharePriceRef.value?.setData(
							res.stationServiceSets,
							optionsS.shareOrg
						);
					});
				}
			}
		});
	}

	let sharePrice = ref(0);
	const shareValue = computed(() => {
		if (!isPercentage.value) {
			return '100';
		}
		return String((100 * 10 - sharePrice.value * 10) / 10);
	});
	let ruleForm : any = reactive({
		id: '',
		stationName: '', //电站名称
		operatorId: undefined as unknown, //归属运营商
		operatorName: '', // 归属运营商名称
		stationStatus: undefined as unknown, //运营状态
		regionCodes: [] as any, // 组件省市区
		provinceCode: '', //省code
		cityCode: '', //市code
		areaCode: '', //区code
		areaCodeName: '', //省市区名称
		address: '', // 详情地址
		stationLng: '', //经度
		stationLat: '', //纬度
		stationAddress: '1', //电站位置 ：1：地上电站 2：地下电站
		isIncrease: false, //是否增容 ：1：增容 0：不增容
		capacitance: '', //可用电容
		property: '1', //场地属性： 1：独立电站 2：混合电站
		stationType: undefined as unknown, //电站类型
		construction: undefined as unknown, //建筑场所
		isMobileVisible: true, //移动端可见性：1：可见 0：不可见
		shareType: '1', //分润模式： 1：固定折扣 2：固定价格
		isOccupationCost: false, //是否收取占用费： 1：是 0：否
		parkBufferTime: '', //停车缓冲时长
		overtimeMoney: '', // 超时计费/元
		overtimeMin: '', // 超时计费/分
		singleDeductionLimit: '', //单笔扣费上限
		isBrake: false, //是否有道闸: 1：有 0：无
		parkExplain: '', // 停车说明
		stationDescribe: '', // 站点描述
		serviceSetupArr: undefined as unknown, // 站点服务设施
		serviceSetup: '',
		baseSetupArr: undefined as unknown, // 周边基础设施
		baseSetup: '',
		openExplain: '', //开放时间说明
		imgMainEntrance: '', //主入口图
		imgFlagPath: '', //标志路径
		imgFullView: '', //电站全景
		imgPilesFeature: '', //电桩特写
		imgOther: '', //其他图片
		qualification: '', //所属资质
		remarks: '', //备注说明
		stationCostBatchNumberInfoPOList: [] as any, // 充电单价
		stationServiceSets: [] as any, // 分润数据
	});

	const errMainEntrance = ref('');
	const checkMainEntrance = (rule : any, value : any, callback : any) => {
		if (!value) {
			if (errMainEntrance.value === 'type') {
				callback(new Error('上传的图片格式不正确'));
			} else if (errMainEntrance.value === 'size') {
				callback(new Error('上传的图片大于2M'));
			}
		}
		callback();
	};
	const errFlagPath = ref('');
	const checkFlagPath = (rule : any, value : any, callback : any) => {
		if (!value) {
			if (errFlagPath.value === 'type') {
				callback(new Error('上传的图片格式不正确'));
			} else if (errFlagPath.value === 'size') {
				callback(new Error('上传的图片大于2M'));
			}
		}
		callback();
	};
	const errFullView = ref('');
	const checkFullView = (rule : any, value : any, callback : any) => {
		if (!value) {
			if (errFullView.value === 'type') {
				callback(new Error('上传的图片格式不正确'));
			} else if (errFullView.value === 'size') {
				callback(new Error('上传的图片大于2M'));
			}
		}
		callback();
	};
	const errPilesFeature = ref('');
	const checkPilesFeature = (rule : any, value : any, callback : any) => {
		if (!value) {
			if (errPilesFeature.value === 'type') {
				callback(new Error('上传的图片格式不正确'));
			} else if (errPilesFeature.value === 'size') {
				callback(new Error('上传的图片大于2M'));
			}
		}
		callback();
	};
	const errOther = ref('');
	const checkOther = (rule : any, value : any, callback : any) => {
		if (!value) {
			if (errOther.value === 'type') {
				callback(new Error('上传的图片格式不正确'));
			} else if (errOther.value === 'size') {
				callback(new Error('上传的图片大于2M'));
			}
		}
		callback();
	};
	const errQualification = ref('');
	const checkQualification = (rule : any, value : any, callback : any) => {
		if (!value) {
			if (errQualification.value === 'type') {
				callback(new Error('上传的图片格式不正确'));
			} else if (errQualification.value === 'size') {
				callback(new Error('上传的图片大于2M'));
			}
		}
		callback();
	};
	const rules = reactive<FormRules>({
		stationName: [{ required: true, message: '请输入电站名称', trigger: 'blur' }],
		operatorId: [
			{ required: true, message: '请选择归属企业', trigger: ['blur', 'change'] },
		],
		stationStatus: [
			{ required: true, message: '请选择运营状态', trigger: ['blur', 'change'] },
		],
		regionCodes: [
			{ required: true, message: '请选择省市区', trigger: ['blur', 'change'] },
		],
		address: [{ required: true, message: '请输入详情地址', trigger: 'blur' }],
		stationAddress: [
			{ required: true, message: '请选择电站位置', trigger: ['blur', 'change'] },
		],
		isIncrease: [
			{ required: true, message: '请选择是否增容', trigger: ['blur', 'change'] },
		],
		property: [
			{ required: true, message: '请选择场地属性', trigger: ['blur', 'change'] },
		],
		stationType: [
			{ required: true, message: '请选择电站类型', trigger: ['blur', 'change'] },
		],
		construction: [
			{ required: true, message: '请选择建筑场所', trigger: ['blur', 'change'] },
		],
		isMobileVisible: [
			{
				required: true,
				message: '请选择移动端可见性',
				trigger: ['blur', 'changer'],
			},
		],
		shareType: [
			{ required: true, message: '请选择分润模式', trigger: ['blur', 'change'] },
		],
		isOccupationCost: [
			{
				required: true,
				message: '请选择是否收取占用费',
				trigger: ['blur', 'changer'],
			},
		],
		parkBufferTime: [
			{ required: true, message: '请输入停车缓冲时长', trigger: 'blur' },
			{
				pattern: IS_INT_0,
				message: '请输入正确的停车缓冲时长，整数',
				trigger: 'blur',
			},
		],
		overtimeMoney: [
			{ required: true, message: '请输入超时计费单价', trigger: 'blur' },
			{
				pattern: IS_DECIMAL_2,
				message: '单价精确到2位小数',
				trigger: 'blur',
			},
		],
		overtimeMin: [
			{ required: true, message: '请输入超时计费时长', trigger: 'blur' },
			{
				pattern: IS_INT,
				message: '时长为正整数',
				trigger: 'blur',
			},
		],
		singleDeductionLimit: [
			{ required: true, message: '请输入单笔扣费上限', trigger: 'blur' },
			{
				pattern: IS_DECIMAL_2,
				message: '请输入正确的单笔扣费上限，精确到2位小数',
				trigger: 'blur',
			},
		],
		isBrake: [
			{ required: true, message: '请选择场站道闸', trigger: ['blur', 'change'] },
		],
		parkExplain: [{ required: true, message: '请输入停车说明', trigger: 'blur' }],
		stationDescribe: [
			{ required: true, message: '请输入站点描述', trigger: 'blur' },
		],
		imgMainEntrance: [{ validator: checkMainEntrance, trigger: 'change' }],
		imgFlagPath: [{ validator: checkFlagPath, trigger: 'change' }],
		imgFullView: [{ validator: checkFullView, trigger: 'change' }],
		imgPilesFeature: [{ validator: checkPilesFeature, trigger: 'change' }],
		imgOther: [{ validator: checkOther, trigger: 'change' }],
		qualification: [{ validator: checkQualification, trigger: 'change' }],
	});

	let isPercentage = ref(false);
	const setPercentage = (flag : boolean) => {
		isPercentage.value = flag;
	};
	const totalPercentage = (num : number) => {
		sharePrice.value = num;
	};
	const clickAdd = async () => {
		setPercentage(true);
		if (optionsS.shareOrg.length === 0 && ruleForm.operatorId) {
			optionsS.shareOrg = await getOrgData(ruleForm.operatorId);
		}
		nextTick(() => {
			sharePercentageRef?.value?.getOrgData(optionsS.shareOrg);
		});
	};

	const changeShareType = async () => {
		if (ruleForm.shareType === '2') {
			if (optionsS.shareOrg.length === 0 && ruleForm.operatorId) {
				optionsS.shareOrg = await getOrgData(ruleForm.operatorId);
			}
			setPercentage(false);
			sharePriceRef?.value?.getOrgData(optionsS.shareOrg);
		} else if (ruleForm.shareType === '1' && isPercentage.value) {
			if (optionsS.shareOrg.length === 0 && ruleForm.operatorId) {
				optionsS.shareOrg = await getOrgData(ruleForm.operatorId);
			}
			sharePercentageRef?.value?.getOrgData(optionsS.shareOrg);
		}
	};

	const handleChangeOrg = async (e : any) => {
		ruleForm.operatorId = e;
		if (ruleForm.operatorId) {
			if (
				(ruleForm.shareType === '1' && isPercentage.value) ||
				ruleForm.shareType === '2'
			) {
				optionsS.shareOrg = await getOrgData(ruleForm.operatorId);
			}
		} else {
			optionsS.shareOrg = [];
		}
		changeShareType();
	};
	const handleChangeOrgStatus = (e : any) => {
		ruleForm.stationStatus = e;
	};
	const handleChangeType = (e : any) => {
		ruleForm.stationType = e;
	};
	const handleChangeConstruction = (e : any) => {
		ruleForm.construction = e;
	};
	const handleChangeService = (e : any) => {
		ruleForm.serviceSetupArr = e.filter((item : any) => item);
		ruleForm.serviceSetup = e ? e.toString() : '';
	};
	const handleChangeBase = (e : any) => {
		ruleForm.baseSetupArr = e.filter((item : any) => item);
		ruleForm.baseSetup = e ? e.toString() : '';
	};
	const regionRef = ref();
	const handleChangeRregion = (e : any) => {
		if (e) {
			ruleForm.regionCodes = e;
			ruleForm.areaCode = e[2];
			ruleForm.cityCode = e[1];
			ruleForm.provinceCode = e[0];
			const node = regionRef.value?.getCheckedNodes()[0];
			console.log('node---', node.data);
			ruleForm.areaCodeName = `${node.pathLabels[0]}${node.pathLabels[1]}${node.pathLabels[2]}`;
		} else {
			ruleForm.regionCodes = [];
			ruleForm.areaCode = '';
			ruleForm.cityCode = '';
			ruleForm.provinceCode = '';
			ruleForm.areaCodeName = '';
		}
	};

	const clickAddress = async () => {
		try {
			await ruleFormRef.value?.validateField(['regionCodes', 'address']);
		} catch (e : any) {
			return;
		}
		const obj = await mapRef.value?.parseAddress(
			`${ruleForm.areaCodeName}${ruleForm.address}`
		);
		ruleForm.stationLat = obj.lat;
		ruleForm.stationLng = obj.lng;
	};

	const changeLngLat = async () => {
		try {
			await ruleFormRef.value?.validateField(['stationLng', 'stationLat']);
		} catch (e : any) {
			return;
		}
		if (ruleForm.stationLng && ruleForm.stationLat) {
			mapRef.value?.addMarker(ruleForm.stationLng, ruleForm.stationLat);
		}
	};

	const setLocation = (lng : any, lat : any) => {
		ruleForm.stationLat = lat;
		ruleForm.stationLng = lng;
	};

	const setRegion = (item : any) => {
		if (item) {
			const codeStr = window.localStorage.getItem('region-code') || '';
			if (!codeStr.includes(item.code)) {
				return;
			}
			ruleForm.areaCode = item.code;
			ruleForm.cityCode = `${item.code.substring(0, 4)}00`;
			ruleForm.provinceCode = `${item.code.substring(0, 2)}0000`;
			ruleForm.regionCodes = [
				ruleForm.provinceCode,
				ruleForm.cityCode,
				ruleForm.areaCode,
			];
			ruleForm.areaCodeName = item.name;
		} else {
			ruleForm.areaCode = '';
			ruleForm.cityCode = '';
			ruleForm.provinceCode = '';
			ruleForm.regionCodes = [];
			ruleForm.areaCodeName = '';
		}
	};

	const showPrice = (id : any) => {
		dialogPriceRef.value?.show(id);
	};

	//主入口图
	const handleSuccessMainEntrance = (val : any) => {
		ruleForm.imgMainEntrance = val;
		ruleFormSetRef?.value?.validateField('imgMainEntrance');
	};
	const handleErrorMainEntrance = () => {
		errMainEntrance.value = 'error';
		ruleFormSetRef?.value?.validateField('imgMainEntrance');
	};
	const beforeUploadMainEntrance = (type : string) => {
		errMainEntrance.value = type;
		if (type) {
			ruleFormSetRef?.value?.validateField('imgMainEntrance');
		}
	};
	//标志路径
	const handleSuccessFlagPath = (val : any) => {
		ruleForm.imgFlagPath = val;
		ruleFormSetRef?.value?.validateField('imgFlagPath');
	};
	const handleErrorFlagPath = () => {
		errFlagPath.value = 'error';
		ruleFormSetRef?.value?.validateField('imgFlagPath');
	};
	const beforeUploadFlagPath = (type : string) => {
		errFlagPath.value = type;
		if (type) {
			ruleFormSetRef?.value?.validateField('imgFlagPath');
		}
	};
	//电站全景
	const handleSuccessFullView = (val : any) => {
		ruleForm.imgFullView = val;
		ruleFormSetRef?.value?.validateField('imgFullView');
	};
	const handleErrorFullView = () => {
		errFullView.value = 'error';
		ruleFormSetRef?.value?.validateField('imgFullView');
	};
	const beforeUploadFullView = (type : string) => {
		errFullView.value = type;
		if (type) {
			ruleFormSetRef?.value?.validateField('imgFullView');
		}
	};
	//电桩特写
	const handleSuccessPilesFeature = (val : any) => {
		ruleForm.imgPilesFeature = val;
		ruleFormSetRef?.value?.validateField('imgPilesFeature');
	};
	const handleErrorPilesFeature = () => {
		errPilesFeature.value = 'error';
		ruleFormSetRef?.value?.validateField('imgPilesFeature');
	};
	const beforeUploadPilesFeature = (type : string) => {
		errPilesFeature.value = type;
		if (type) {
			ruleFormSetRef?.value?.validateField('imgPilesFeature');
		}
	};
	//其他图片
	const handleSuccessOther = (val : any) => {
		ruleForm.imgOther = val;
		ruleFormSetRef?.value?.validateField('imgOther');
	};
	const handleErrorOther = () => {
		errOther.value = 'error';
		ruleFormSetRef?.value?.validateField('imgOther');
	};
	const beforeUploadOther = (type : string) => {
		errOther.value = type;
		if (type) {
			ruleFormSetRef?.value?.validateField('imgOther');
		}
	};
	//所属资质
	const handleSuccessQualification = (val : any) => {
		ruleForm.qualification = val;
		ruleFormSetRef?.value?.validateField('qualification');
	};
	const handleErrorQualification = () => {
		errQualification.value = 'error';
		ruleFormSetRef?.value?.validateField('qualification');
	};
	const beforeUploadQualification = (type : string) => {
		errQualification.value = type;
		if (type) {
			ruleFormSetRef?.value?.validateField('qualification');
		}
	};

	const back = () => {
		router.go(-1);
	};
	const emit = defineEmits(['clear-cache']);
	const onSubmit = async () => {
		if (
			!ruleFormRef.value ||
			!ruleFormShareRef.value ||
			!ruleFormSiteRef.value ||
			!ruleFormSetRef.value
		)
			return;
		errMainEntrance.value = '';
		errFlagPath.value = '';
		errFullView.value = '';
		errPilesFeature.value = '';
		errOther.value = '';
		errQualification.value = '';
		let comData = [] as any;
		let flag = true;
		let objError = {} as any;
		comData = await Promise.all([
			ruleFormRef.value.validate((e : any, fields : any) => {
				flag = flag ? e : false;
				if (!e) {
					objError = { ...objError, ...fields };
				}
			}),
			ruleFormShareRef.value.validate((e : any, fields : any) => {
				flag = flag ? e : false;
				if (!e) {
					objError = { ...objError, ...fields };
				}
			}),
			ruleFormSiteRef.value.validate((e : any, fields : any) => {
				flag = flag ? e : false;
				if (!e) {
					objError = { ...objError, ...fields };
				}
			}),
			ruleFormSetRef.value.validate((e : any, fields : any) => {
				flag = flag ? e : false;
				if (!e) {
					objError = { ...objError, ...fields };
				}
			}),
			stationPriceRef?.value?.getData(),
			sharePriceRef?.value?.getData(),
			sharePercentageRef?.value?.getData(),
		]);
		if (
			!flag ||
			comData[4] === false ||
			comData[5] === false ||
			comData[6] === false
		) {
			for (const key in ruleForm) {
				if (objError[key]) {
					ruleFormRef.value.scrollToField(key);
					ruleFormShareRef.value.scrollToField(key);
					ruleFormSiteRef.value.scrollToField(key);
					ruleFormSetRef.value.scrollToField(key);
					break;
				}
			}
			return;
		}
		if (comData[4]) {
			ruleForm.stationCostBatchNumberInfoPOList = comData[4];
		}
		if (ruleForm.shareType === '2') {
			if (comData[5]) {
				ruleForm.stationServiceSets = comData[5];
			} else {
				ruleForm.stationServiceSets = [];
			}
		}
		if (ruleForm.shareType === '1') {
			if (comData[6]) {
				ruleForm.stationServiceSets = comData[6];
			} else {
				ruleForm.stationServiceSets = [];
			}
		}
		console.log('ruleForm---', ruleForm);
		if (id) {
			updateStation(ruleForm).then((res : any) => {
				if (res) {
					emit('clear-cache');
					back();
				}
			});
		} else {
			addStation(ruleForm).then((res : any) => {
				if (res) {
					ElMessageBox.confirm(
						'电站添加成功，是否立即前往为电站添加电桩？',
						'提示',
						{
							confirmButtonText: '前往添加',
							cancelButtonText: '暂不添加',
							type: 'success',
						}
					)
						.then(() => {
							// 判断是否有新增电桩权限
							if (bntAuth('pileList.add')) {
								router.replace({
									name: 'pileAdd',
									query: { stationId: res.id },
								});
								emit('clear-cache');
							} else {
								ElMessage({
									showClose: true,
									message: '您没有新增电桩权限，请联系管理员！',
									type: 'warning',
								});
								emit('clear-cache');
								back();
							}
						})
						.catch(() => {
							emit('clear-cache');
							back();
						});
				}
			});
		}
	};
</script>

<style lang="scss" scoped>
	.address-wrap,
	.site-wrap {
		display: flex;
	}

	.main-wrap .edit-page-wrap .edit-form-wrap {
		.address-wrap {
			:deep(.el-form-item__error) {
				width: 140px;
			}

			.input-wrap {
				width: 194px;
			}
		}

		.site-wrap .input-wrap {
			width: 134.5px;
		}
	}
</style>